package com.dhecp.project.system.controller;

import java.util.*;

import com.dhecp.project.flowable.domain.ActHistoricInstance;
import com.dhecp.project.storage.domain.HwStorage;
import com.dhecp.project.system.domain.SysDictionaryForMobileField;
import com.dhecp.project.system.service.SysDictionaryForMobileFieldService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.controller.BaseController;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.enums.ControlType;
import com.dhecp.core.enums.DataLimitType;
import com.dhecp.core.enums.FieldFrontAlignType;
import com.dhecp.core.enums.FieldFrontTempletType;
import com.dhecp.core.enums.FieldSearchType;
import com.dhecp.core.enums.SQLConditionsType;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.common.domain.MapKeyAndValue;
import com.dhecp.project.common.service.MapKeyAndValueService;
import com.dhecp.project.system.domain.SysDictionaryForField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 字段数据字典 控制层
 * @author lwl
 * @version 2019年11月1日
 */
@Controller
@RequestMapping("/system/dictionaryforfield")   
public class SysDictionaryForFieldController extends BaseController{

	private String prefix = "system/dictionaryforfield";
	private String moduleTable = ModuleTable.DICTIONARY_FOR_FIELD;
	
	@Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private SysDictionaryForMobileFieldService sysDictionaryForMobileFieldService;
	
	@Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;
	
	@Autowired
    private MapKeyAndValueService mapKeyAndValueService;
	
	/**
     * 打开字段数据字典列表
     * @param 
     * @return ModelAndView
     * @author lwl
     */
	@RequiresPermissions("system:dictionaryforfield:view")
    @GetMapping()
    public ModelAndView dataList(@RequestParam Map<String, Object> params)
    {
		params.put("moduleTable", moduleTable);
    	params.put("entity", new SysDictionaryForField()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	Subject userSubject = ShiroUtils.getSubject();
    	Integer toolBarWidth = 0;
    	if (userSubject.isPermitted("system:dictionaryforfield:delete")){	//当前登录用户主体是否有删除的权限
            params.put("checkBox", "yes"); //生成表格gridColumns时包含复选
            toolBarWidth = toolBarWidth + 70;
    	}
    	if (userSubject.isPermitted("system:dictionaryforfield:edit")){ //当前登录用户主体是否有修改的权限
            toolBarWidth = toolBarWidth + 110;
    	}
    	params.put("toolBarWidth", toolBarWidth);
    	params.put("readOnly", false);
		ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String,Object> controlType = TypeUtils.EnumToMap(ControlType.class);
        Map<String,Object> fieldFrontTempletType = TypeUtils.EnumToMap(FieldFrontTempletType.class);
        Map<String,Object> conditionsType = TypeUtils.EnumToMap(SQLConditionsType.class);
        Map<String,Object> dataLimitType = TypeUtils.EnumToMap(DataLimitType.class);
        dataLimitType.remove("CompanysData"); //去除集团权限，字段属性配置中使用部门权限标识
        dataLimitType.remove("AllData"); //去除全部权限
        Map<String,Object> fieldFrontAlignType = TypeUtils.EnumToMap(FieldFrontAlignType.class);
        Map<String,Object> fieldSearchType = TypeUtils.EnumToMap(FieldSearchType.class);
        List<MapKeyAndValue> mapKeyAndValueList = mapKeyAndValueService.queryMapKeyAndValueForBaseInfo(params);
        for (MapKeyAndValue mapKeyAndValue : mapKeyAndValueList){	//加入基础数据类型
        	if (mapKeyAndValue.getMapKey() != null && !"".equals(mapKeyAndValue.getMapKey().toString())){
            	fieldSearchType.put(mapKeyAndValue.getMapKey().toString(), mapKeyAndValue.getMapValue().toString());
        	}
        }
        
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("controlType",controlType); //前台控件类型 下拉内容
        mv.addObject("fieldFrontTempletType",fieldFrontTempletType); //前台显示类型 下拉内容
        mv.addObject("conditionsType",conditionsType); //查询条件类型 下拉内容
        mv.addObject("dataLimitType",dataLimitType); //数据权限字段 下拉内容
        mv.addObject("fieldFrontAlignType",fieldFrontAlignType); //前台列内容位置 下拉内容
        mv.addObject("fieldSearchType",fieldSearchType); //待选数据类型 下拉内容
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("moduleTable",moduleTable); //待选数据类型 下拉内容
        mv.setViewName(prefix + "/dictionaryforfield");
		return mv;
    }
	
	/**
     * 直接查询所有的字段数据字典
     * @param params
     * @return TableDataInfo
     * @author lwl
     */
	@GetMapping("/list")
    @RequiresPermissions("system:dictionaryforfield:list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params)
    {
		params.put("moduleTable", moduleTable);
        List<SysDictionaryForField> dictlist = new ArrayList<SysDictionaryForField>();
        try {
        	dictlist = dictionaryForFieldService.queryDictionaryForField(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());            
        }
        return getDataTable(dictlist);
    }
	
	/**
     * 根据表名查询功能字段
     * @param params
     * @return TableDataInfo
     * @author lwl
     */
	@RequiresPermissions("system:dictionaryforfield:list")
    @RequestMapping("/tablelist")
    @ResponseBody
    public TableDataInfo tablelist(@RequestParam Map<String, Object> params)    {
        List<SysDictionaryForField> dictList = new ArrayList<SysDictionaryForField>();
		try {
			dictList = dictionaryForFieldService.queryDictionaryForFieldByTableName(params);
		} catch (Exception e) {
			e.printStackTrace();
			return getDataTable(this.getExceptionMessage(e).toString());
		}
        return getDataTable(dictList);
    }
	
	/**
     * 打开功能字段新增页
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @RequiresPermissions("system:dictionaryforfield:add")
    @GetMapping("/add")
    public ModelAndView add(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String,Object> controlType = TypeUtils.EnumToMap(ControlType.class);
        Map<String,Object> fieldFrontTempletType = TypeUtils.EnumToMap(FieldFrontTempletType.class);
        Map<String,Object> conditionsType = TypeUtils.EnumToMap(SQLConditionsType.class);
        Map<String,Object> dataLimitType = TypeUtils.EnumToMap(DataLimitType.class);
        dataLimitType.remove("CompanysData"); //去除集团权限，字段属性配置中使用部门权限标识
        dataLimitType.remove("AllData"); //去除全部权限
        Map<String,Object> fieldFrontAlignType = TypeUtils.EnumToMap(FieldFrontAlignType.class);
        Map<String,Object> fieldSearchType = TypeUtils.EnumToMap(FieldSearchType.class);
        List<MapKeyAndValue> mapKeyAndValueList = mapKeyAndValueService.queryMapKeyAndValueForBaseInfo(params);
        for (MapKeyAndValue mapKeyAndValue : mapKeyAndValueList){	//加入基础数据类型
        	if (mapKeyAndValue.getMapKey() != null && !"".equals(mapKeyAndValue.getMapKey().toString())){
            	fieldSearchType.put(mapKeyAndValue.getMapKey().toString(), mapKeyAndValue.getMapValue().toString());
        	}
        }
        
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("pageType","add");
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("controlType",controlType); //前台控件类型 下拉内容
        mv.addObject("fieldFrontTempletType",fieldFrontTempletType); //前台显示类型 下拉内容
        mv.addObject("conditionsType",conditionsType); //查询条件类型 下拉内容
        mv.addObject("dataLimitType",dataLimitType); //数据权限字段 下拉内容
        mv.addObject("fieldFrontAlignType",fieldFrontAlignType); //前台列内容位置 下拉内容
        mv.addObject("fieldSearchType",fieldSearchType); //待选数据类型 下拉内容
        mv.setViewName(prefix + "/dictionaryforfield_add");
        return mv;
    }
    
    /**
     * 新增功能字段——数据提交
     * @param dictionaryForFieldItems 必要参数：对应实体类的json格式字符串
     * @return AjaxResult
     * @author lwl
     */
    @RequiresPermissions("system:dictionaryforfield:add")
    @Log(title = "新增字段", businessType = BusinessType.INSERT)
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("dictionaryForFieldItems") == null || params.get("dictionaryForFieldItems") == ""){
        	return AjaxResult.error("缺少参数dictionaryForFieldItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= dictionaryForFieldService.insertDictionaryForField(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 打开字段数据字典修改页面
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @RequiresPermissions("system:dictionaryforfield:edit")
    @GetMapping("/edit")
    public ModelAndView edit(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
    	ModelAndView mv = this.getModelAndView();
        Map<String,Object> controlType = TypeUtils.EnumToMap(ControlType.class);
        Map<String,Object> fieldFrontTempletType = TypeUtils.EnumToMap(FieldFrontTempletType.class);
        Map<String,Object> conditionsType = TypeUtils.EnumToMap(SQLConditionsType.class);
        Map<String,Object> dataLimitType = TypeUtils.EnumToMap(DataLimitType.class);
        dataLimitType.remove("CompanysData"); //去除集团权限，字段属性配置中使用部门权限标识
        dataLimitType.remove("AllData"); //去除全部权限
        Map<String,Object> fieldFrontAlignType = TypeUtils.EnumToMap(FieldFrontAlignType.class);
        Map<String,Object> fieldSearchType = TypeUtils.EnumToMap(FieldSearchType.class);
        List<MapKeyAndValue> mapKeyAndValueList = mapKeyAndValueService.queryMapKeyAndValueForBaseInfo(params);
        for (MapKeyAndValue mapKeyAndValue : mapKeyAndValueList){	//加入基础数据类型
        	if (mapKeyAndValue.getMapKey() != null && !"".equals(mapKeyAndValue.getMapKey().toString())){
            	fieldSearchType.put(mapKeyAndValue.getMapKey().toString(), mapKeyAndValue.getMapValue().toString());
        	}
        }
        
        if (mv.isEmpty()){
            mv = this.gotoModelAndViewErrorPage(params, "guid","字段编号");
        }
        if (mv.isEmpty()){
            AjaxResult ajaxResult = new AjaxResult();
            try{
            	SysDictionaryForField dictionaryForField = dictionaryForFieldService.queryDictionaryForFieldByGuid(params.get("guid").toString());
                if (dictionaryForField == null){
                    ajaxResult = AjaxResult.error("没有符合条件的数据。");
                }else{
                    ajaxResult = AjaxResult.success("查询成功。");
                }
                mv.addObject("dictionaryForField", dictionaryForField);
                mv.addObject("moduleTable", dictionaryForField.getModuleTable());
            }catch(Exception e){
                ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
            }
            mv.addObject("ajaxResult", ajaxResult);
            mv.addObject("controlType",controlType); //前台控件类型 下拉内容
            mv.addObject("fieldFrontTempletType",fieldFrontTempletType); //前台显示类型 下拉内容
            mv.addObject("conditionsType",conditionsType); //查询条件类型 下拉内容
            mv.addObject("dataLimitType",dataLimitType); //数据权限字段 下拉内容
            mv.addObject("fieldFrontAlignType",fieldFrontAlignType); //前台列内容位置 下拉内容
            mv.addObject("fieldSearchType",fieldSearchType); //待选数据类型 下拉内容
            mv.setViewName(prefix + "/dictionaryforfield_add");
        }
        return mv;
    }

    /**
     * 修改功能字段信息--提交数据
     * @param dictionaryForFieldItems
     * @return AjaxResult
     */
    @RequiresPermissions("system:dictionaryforfield:edit")
    @Log(title = "修改功能字段信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editPost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        if (params.get("dictionaryForFieldItems") == null || params.get("dictionaryForFieldItems") == ""){
        	return AjaxResult.error("缺少参数dictionaryForFieldItems【对应实体类的json格式字符串】。");
        }
        try {
            ajaxResult= dictionaryForFieldService.updateDictionaryForField(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    
    /**
     * 删除功能字段信息
     * @param dictionaryForFieldItems
     * @return AjaxResult
     */
    @RequiresPermissions("system:userbindrole:delete")
    @Log(title = "删除功能字段", businessType = BusinessType.DELETE)
    @PostMapping("/delete")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult delete(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= dictionaryForFieldService.deleteDictionaryForField(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    /**
     * 复制功能数据字典
     * @param params
     * @return AjaxResult
     * @author lwl
     */
    @RequiresPermissions("system:dictionaryformobilefield:add")
    @Log(title = "复制到移动端", businessType = BusinessType.INSERT)
    @PostMapping("/copyToMobile")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult copyToMobile(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if (params.get("moduleTable") == null || params.get("moduleTable") == ""){
                return AjaxResult.error("缺少必要参数：单据功能唯一标识[moduleTable]");
            }else {
                List<SysDictionaryForField> list = dictionaryForFieldService.getDictionaryForFieldModuleTableData(params.get("moduleTable").toString());
                sysDictionaryForMobileFieldService.deleteDictionaryForFieldBymoduleTable(params.get("moduleTable").toString());

                for (SysDictionaryForField sysDictionaryForField: list
                ) {
                    SysDictionaryForMobileField sysDictionaryForMobileField = new SysDictionaryForMobileField();
                    BeanUtils.copyProperties(sysDictionaryForField,sysDictionaryForMobileField);
                    sysDictionaryForMobileFieldService.addDictionaryForMobileField(sysDictionaryForMobileField);
                }
            }
            ajaxResult= AjaxResult.success("操作成功");
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }

    @RequiresPermissions("system:dictionaryformobilefield:add")
    @Log(title = "同步列名", businessType = BusinessType.INSERT)
    @PostMapping("/tblm")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult tblm(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            if (params.get("moduleTable") == null || params.get("moduleTable") == ""){
                return AjaxResult.error("缺少必要参数：单据功能唯一标识[moduleTable]");
            }else {
                ajaxResult= dictionaryForFieldService.tblm(params.get("moduleTable").toString());
            }
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}
